package com.yunli.mall.service.impl;

import com.yunli.mall.common.util.IdGenUtil;
import com.yunli.mall.enums.SeckillStateEnum;
import com.yunli.mall.repository.PayOrderMapper;
import com.yunli.mall.repository.SeckillMapper;
import com.yunli.mall.schema.entity.PayOrder;
import com.yunli.mall.schema.entity.Seckill;
import com.yunli.mall.schema.response.SeckillExecution;
import com.yunli.mall.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author yaolonglong
 * @date 2020/9/20 19:34
 */
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private SeckillMapper seckillMapper;

    @Override
    public synchronized SeckillExecution executor(String seckillId, String phone) {
        Seckill seckill = seckillMapper.selectById(seckillId);
        if(seckill.getInventory() > 0) {
            seckill.setInventory(seckill.getInventory() - 1);
            seckillMapper.updateById(seckill);
            PayOrder payOrder = new PayOrder();
            payOrder.setId(IdGenUtil.nextId());
            payOrder.setSeckillId(seckillId);
            payOrder.setUserPhone(phone);
            payOrder.setState(0);
            payOrderMapper.insert(payOrder);
            return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS);
        }else{
            return new SeckillExecution(seckillId, SeckillStateEnum.ACCESS_LIMIT);
        }
    }

    @Override
    public int result(String seckillId, String phone) {
        return 0;
    }
}
